package com.example.oj_springboot.service;

import com.example.oj_springboot.api.config.exception.CodeNullException;
import com.example.oj_springboot.model.CompileResponse;
import com.example.oj_springboot.service.util.Task;
import com.example.oj_springboot.mapper.ProblemMapper;
import com.example.oj_springboot.model.CompileRequest;
import com.example.oj_springboot.model.Problem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

@Service
public class CompileService {

    @Resource
    private ProblemMapper problemMapper;

    public CompileResponse compile(CompileRequest compileRequest) throws Exception {
        Problem problem =  problemMapper.getOne(compileRequest.getId());
        if (problem == null){
            throw new Exception();
        }

        //拼接代码
        String code = mergeCode(compileRequest.getCode(), problem.getTestCode());
        if (StringUtils.isBlank(code)){
            throw new CodeNullException();
        }

        //创建一个Task实例，调用complieAndRun方法来执行
        Task task = new Task();
        CompileResponse compileResponse = task.compileAndRun(code);
        return compileResponse;
    }

    /**
     * 拼接代码
     * @param requestCode
     * @param testCode
     * @return
     */
    private String mergeCode(String requestCode, String testCode) {
        int pos = requestCode.lastIndexOf("}");
        if (pos == -1) {
            return null;
        }
        return requestCode.substring(0, pos) + testCode + "}";
    }
}